package com.jinhua.huaojcodesandbox.controller;

import cn.hutool.core.util.StrUtil;
import com.jinhua.huaojcodesandbox.JavaDockerCodeSandBox;
import com.jinhua.huaojcodesandbox.model.ExecuteCodeRequest;
import com.jinhua.huaojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {
//    定义鉴权请求头
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secrety";


    @Resource
    private JavaDockerCodeSandBox codeSandBox;

    @GetMapping("/hello")
    public String index() {
        return "Hello World";
    }

    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest
            , HttpServletRequest request, HttpServletResponse response){
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if (StrUtil.isBlank(header) || !AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            System.out.println("请求权限校验未通过");
            throw new RuntimeException("无权限");
        }
        if (executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        return codeSandBox.executeCode(executeCodeRequest);

    }
}
